﻿namespace InkType.ViewModel

open InkType.ViewModel.SavedTypefaces
open System
open System.Collections.Generic
open System.Collections.ObjectModel
open System.ComponentModel
open System.Windows
open System.Windows.Ink
open System.Windows.Input
open System.Windows.Media


type [<AllowNullLiteral>] CharacterBlockViewModel private (block : CharacterBlock, glyphs : GlyphViewModel [], __) =
    inherit DependencyObject ()

    static member val GlyphsProperty =
        Dp.reg<GlyphViewModel [], CharacterBlockViewModel> "Glyphs"
            (Dp.Meta ([| |]))

    static member val SelectedItemProperty =
        Dp.reg<GlyphViewModel, CharacterBlockViewModel> "SelectedItem"
            (Dp.Meta (
                Unchecked.defaultof<GlyphViewModel>,
                fun x (oldval, _) -> if oldval <> null then oldval.OnExit ()))

    new (block, glyphs) as x =
        CharacterBlockViewModel (block, glyphs, ())
        then
            x.Glyphs <- glyphs |> Array.copy
            x.SelectedItem <- glyphs.[0]

    member x.Model = block

    member x.Glyphs
        with get () = x.GetValue CharacterBlockViewModel.GlyphsProperty :?> GlyphViewModel []
        and set (v : GlyphViewModel []) = x.SetValue (CharacterBlockViewModel.GlyphsProperty, box v)

    member x.SelectedItem
        with get () = x.GetValue CharacterBlockViewModel.SelectedItemProperty :?> GlyphViewModel
        and set (v : GlyphViewModel) = x.SetValue (CharacterBlockViewModel.SelectedItemProperty, box v)

    member x.ShuffleCommand =
        fun () ->
            let r = Random (0x2D2816FE)
            let glyphs = x.Glyphs |> Array.copy
            for i in glyphs.Length - 1 .. -1 .. 0 do
                let j = r.Next (i + 1)
                let temp = glyphs.[i]
                glyphs.[i] <- glyphs.[j]
                glyphs.[j] <- temp
            x.Glyphs <- glyphs
        |> Command.Relay

    member x.UnshuffleCommand =
        fun () ->
            x.Glyphs <- glyphs |> Array.copy
        |> Command.Relay

    member x.OnExit () =
        match x.SelectedItem with
        | null -> ()
        | item -> item.OnExit ()




